package com.bank;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.text.TextUtils;

import com.entity.User;
import com.show.api.util.StringUtils;
import com.utils.ChatClient;
import com.utils.Constants;
import com.utils.FileHelper;
import com.utils.ImageView;
import com.utils.LogToFile;
import com.utils.Util;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.PAUSE;
import static com.utils.ChatClient.addWorkTime;
import static com.utils.ChatClient.bankInfo;
import static com.utils.ChatClient.request;
import static com.utils.ChatClient.userInfo;

/**
 * 项目名称：yzf
 * 类描述：云闪付查账脚本
 * 创建时间：2019/4/17 14:13
 * 修改时间：2019/4/17 14:13
 * 修改备注：
 */
@RunWith(AndroidJUnit4.class)
public class UnionPay {

    private final String bankName = "云闪付";
    private UiDevice mDevice;
    private int screenHeight;
    private static String bank_name = "YSF";
    static Context context = InstrumentationRegistry.getTargetContext();

    private User user;
    //    private String userResultCacheFile;//缓存上次上传订单文件名
    private String QRCodeUpdateTimeFile;//缓存上次上传二维码时间
    private int dragFlag = 1;//列表滑动次数
    private List<String> itemInfoList = new ArrayList<>();
    private List<String> itemResultCacheInfoList = new ArrayList<>();
    private String userOrderListResultCacheFile;//用户当天上报账单缓存文件路径
    private String date;
    private String carrier;

    @Test
    public void demo() throws UiObjectNotFoundException {
        LogToFile.init(context, Constants.PROT);
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        // 启动云闪付
        Constants.scriptToStart(mDevice, bankName);
        screenHeight = Constants.getScreenHeight(context, bankName);
        // 获取账户信息
        Constants.getAccountInformation(Constants.getMethod(0));
        Constants.tryingToReadAccountInformation(mDevice, bankName);
        carrier = android.os.Build.MODEL;
        //检查usb连接状态
        while (true) {
            if (Constants.STATE_USB) {
//                networkRefresh();
                joinApp();
                break;
            }
        }
    }

    /**
     * 进入APP
     *
     * @throws UiObjectNotFoundException 异常捕获
     */
    private void joinApp() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_10) {
                showMsg("无版本跟新弹窗");
                break;
            }
            UiObject mBT_bottom = mDevice.findObject(new UiSelector().resourceId("com.unionpay:id/btn_cancel").text("稍候再说"));
            if (mBT_bottom.exists()) {
                showMsg("取消版本跟新弹窗");
                mBT_bottom.click();
                sleep(2000);
                break;
            }
        }
        // 获取账号信息，确认登陆成功
        requestUserInfo();
        // 文件创建及清理缓存
        readOrderListFile();

        UploadLogic();

    }

    /**
     * 读取当天上传账单缓存纪律
     */
    private void readOrderListFile() {
        userOrderListResultCacheFile = user.getUserName() + bank_name + Util.getStandardDate("") + ".txt";
        try {
            showMsg("缓存File" + userOrderListResultCacheFile);
            FileHelper.createSDFile(userOrderListResultCacheFile);
            String orderListString = FileHelper.readSDFile(userOrderListResultCacheFile);
            if (StringUtils.isEmpty(orderListString)) {
                showMsg("清空账单集合");
                itemResultCacheInfoList.clear();
            } else {
                String[] orders = orderListString.split("\n");
                itemResultCacheInfoList = new ArrayList<>(Arrays.asList(orders));
                showMsg("itemResultCacheInfoList.size()===" + itemResultCacheInfoList.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void UploadLogic() throws UiObjectNotFoundException {
        while (true) {
            ChatClient.request();
            // 每次登陆上报截图 2020年3月10日16:09:29
            if (UpdateQRCode() || newLogin) {
                handleQRCodeBase64();
                back();
                sleep(ChatClient.overtime_3);
                back();
                sleep(ChatClient.overtime_3);
                back();
            }
            joinOrderListPage();
            dragFlag = 1;
            if (PAUSE) {
                sleep(1000);
                showMsg("PAUSE");
                reportOrderList();
            } else {//检测上报账单
                showMsg("开始上报");
                orderListAuditDetection();
            }
            sleep(ChatClient.overtime_3);
            backMainPage();
        }
    }


    private void requestUserInfo() {
        //获取账号信息
        ChatClient.start();
        while (true) {
            if (userInfo.equals("")) {
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_GET_BANK_LOGIN_INFO_P + "'}</YZF>");
                sleep(5000);
            } else {
                user = new User();
                String[] res = userInfo.split(" ");
                for (int i = 0; i < res.length; i++) {
                    switch (i) {
                        case 0:
                            user.setUserName(res[0]);
                            break;
                        case 1:
                            user.setPwd(res[1]);
                            break;
                        case 2:
                            user.setBankpwd(res[2]);
                            break;
                        case 3:
                            user.setUsbPayPwd(res[3]);
                            break;
                        case 4:
                            user.setUseType(res[4]);
                            break;
                    }
                }
                ChatClient.loginS();
                break;
            }
        }
    }


    private int itemNum = 0;
    private String readYears = null;

    /**
     * 根据客户设置无差别上报查账时间段账单
     */
    public void orderListAuditDetection() throws UiObjectNotFoundException {
        ChatClient.request();
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_3) {
                break;
            }
            UiObject mTV_not_order_list = mDevice.findObject(new UiSelector().className("android.widget.TextView").text
                    ("找不到相关记录"));
            if (mTV_not_order_list.exists()) {
                showMsg("账单页面未刷新出来，返回");
                sleep(ChatClient.overtime_5);
                backMainPage();
                return;
            }
        }

        date = Util.getStandardDate(".");
        String readDate;
        while (true) {
            UiObject mSV = mDevice.findObject(new UiSelector().className("android.widget.ScrollView").index(0));
            if (mSV.exists()) {
                UiObject mVG_childlList = mSV.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
                if (mVG_childlList.exists()) {
                    while (true) {
                        UiObject mVG = mVG_childlList.getChild(new UiSelector().className("android.view.ViewGroup").index
                                (itemNum));
                        if (mVG.exists()) {
                            showMsg("查看第" + itemNum + "条");
                            if (isDateItem(mVG)) {
                                if (checkMonth > 2) {
                                    showMsg("非查询月，退出查询");
                                    backMainPage();
                                    itemNum = 0;
                                    return;
                                }
                                continue;
                            }
                            UiObject mTV1 = mVG.getChild(new UiSelector().className("android.widget.TextView").index(1));
                            if (mTV1.exists()) {
                                String text = mTV1.getText().trim();
                                showMsg("itemText---" + text);
                                if (!StringUtils.isEmpty(text)) {
                                    if (text.contains("向上滑动，查看更多")) {
                                        showMsg("以到底部，上滑");
                                        mDevice.drag(120, screenHeight - 150, 120, screenHeight - 1000, 20);
                                        sleep(ChatClient.overtime_1);
                                    } else {
                                        UiObject mTV0 = mTV1.getFromParent(new UiSelector().className("android.widget.TextView")
                                                .index(0));
                                        showMsg("找到有日期条目，这是第：" + itemNum + "条目");
                                        if (mTV0.exists()) {
                                            String day = mTV0.getText().trim();
                                            if (!StringUtils.isEmpty(day)) {
                                                readDate = readYears + "." + day;
                                                showMsg("日期为" + readDate);
                                                if (Util.isInquireDate(ChatClient.detection.getDate(), readDate)) {
                                                    showMsg("是需要查询的日期");
                                                    UiObject mTV_status = findItemView(mVG);
                                                    if (mTV_status != null) {
                                                        if (mTV_status.exists()) {
                                                            showMsg("存在转账条目");
                                                            mTV_status.click();
                                                            if (joinOrderPage()) {
                                                                showMsg("进入交易详情页");
                                                                boolean b = orderPage(true);
                                                                if (b) {
                                                                    itemNum += 1;
                                                                    back();
                                                                } else {
                                                                    showMsg("不是查询周期账单");
                                                                    backMainPage();
                                                                    return;
                                                                }
                                                            } else {
                                                                showMsg("未进入交易详情页");
                                                            }
                                                        } else {
                                                            showMsg("非入账条目");
                                                            itemNum += 1;
                                                        }
                                                    } else {
                                                        showMsg("未找到" + itemNum + "条目");
                                                        orderListAuditDetection();
                                                        return;
                                                    }
                                                } else {
                                                    showMsg("日期超时，不需要查询");
                                                    itemNum = 0;
                                                    backMainPage();
                                                    return;
                                                }
                                            }
                                        } else {
                                            drag(mVG);
                                            //orderListauditDetection();
                                        }
                                    }
                                } else {
                                    showMsg("无日期条目，可查询");
                                    UiObject mTV_status = findItemView(mVG);
                                    if (mTV_status != null) {
                                        if (mTV_status.exists()) {
                                            showMsg("存在转账条目");
                                            mTV_status.click();
                                            if (joinOrderPage()) {
                                                showMsg("进入交易详情页");
                                                boolean b = orderPage(true);
                                                if (b) {
                                                    itemNum += 1;
                                                    back();
                                                } else {
                                                    showMsg("不是查询周期账单");
                                                    backMainPage();
                                                    return;
                                                }
                                            } else {
                                                showMsg("未进入交易详情页");
                                            }
                                        } else {
                                            showMsg("非入账条目");
                                            itemNum += 1;
                                        }
                                    } else {
                                        showMsg("未找到" + itemNum + "条目");
                                        orderListAuditDetection();
                                        return;
                                    }
                                }
                            } else {
                                drag(mVG);
                            }
                        } else {
                            drag(mVG);
                        }
                    }
                }
            }
        }
    }


    private int checkMonth = 1;

    /**
     * 判定是否是年月条目
     *
     * @param mVG 条目
     * @return 是否有下一页
     * @throws UiObjectNotFoundException 异常捕获
     */
    public boolean isDateItem(UiObject mVG) throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_3) {
                showMsg("日期条目超时");
                return false;
            }
            UiObject mVG_dateChild;
            if (mVG.exists()) {
                if (itemNum == 0) {
                    mVG_dateChild = mVG.getChild(new UiSelector().className("android.widget.TextView")
                            .index(0));
                } else {
                    mVG_dateChild = mVG.getChild(new UiSelector().className("android.widget.TextView")
                            .index(1));
                }
                if (mVG_dateChild.exists()) {
                    String mTV_date = mVG_dateChild.getText().trim();
                    if (mTV_date.contains(".")) {
                        readYears = mTV_date;
                        showMsg("itemNum---" + itemNum + ",date: " + mTV_date);
                        // 判断以过查询月
                        String standardDate = Util.getStandardDate(".");
                        if (!standardDate.contains(readYears)) {
                            String day = Util.getLastDayOfMonth(readYears);
                            if (!Util.isInquireDate(ChatClient.detection.getDate(), readYears + "." + day)) {
                                showMsg("非查询月");
                                checkMonth = 3;
                                return true;
                            }
                        }
                        if (itemNum != 0) {
                            mVG_dateChild.click();
                            sleep(ChatClient.overtime_2);
                            checkMonth += 1;
                        } else {
                            checkMonth = 1;
                        }
                        itemNum += 1;
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }
    }

    /**
     * 上报订单信息
     *
     * @param tradingTime 上报时间
     * @param json        上报的数据
     */
    private boolean uploadOrder(String tradingTime, String json) {
        String date = tradingTime.split(" ")[0];
        if (!StringUtils.isEmpty(date)) {
            date = date.replaceAll("-", ".");
            boolean inquireDate = Util.isInquireDate(ChatClient.detection.getDate(), date);
            if (!inquireDate) {
                return false;
            }
        }
        ChatClient.M_sendTradeInfo_P(json);
        sleep(ChatClient.overtime_1);
        request();
        int flag = 1;
        while (true) {
            if (ChatClient.tradeInfo != null) {
                if (json.contains(ChatClient.tradeInfo.getMark())) {
                    if (ChatClient.tradeInfo.getCode().equals("100000")) {
                        showMsg("上报成功，储存---" + json);
                        String resultCacheOrderItem = json;
                        itemResultCacheInfoList.add(resultCacheOrderItem);
                        resultCacheOrderItem += "\n";
                        FileHelper.addWriteSDFile(true, resultCacheOrderItem, userOrderListResultCacheFile);
                        return true;
                    } else if (ChatClient.tradeInfo.getCode().equals("201030")) {
                        showMsg("上报重复订单---" + json);
                        if (!itemResultCacheInfoList.contains(json)) {
                            showMsg("CacheInfo");
                            String resultCacheOrderItem = json;
                            itemResultCacheInfoList.add(resultCacheOrderItem);
                            resultCacheOrderItem += "\n";
                            FileHelper.addWriteSDFile(true, resultCacheOrderItem, userOrderListResultCacheFile);
                        }
                        return true;
                    } else if (ChatClient.tradeInfo.getCode().equals("200000")) {
                        showMsg("上传返回错误第：" + flag + "次，" + ChatClient.tradeInfo.toString());
                        if (flag == 3) {//上报返回错误循环上报3回退出页面继续下一条
                            return true;
                        }
                        ChatClient.tradeInfo = null;
                        flag += 1;
                        ChatClient.M_sendTradeInfo_P(json);
                        sleep(ChatClient.overtime_2);
                    }
                }
            }
        }
    }

    /**
     * 处理交易记录列表页
     */

    private void reportOrderList() throws UiObjectNotFoundException {
        showMsg("reportOrderList");
        ChatClient.request();
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowTime = System.currentTimeMillis();
            if ((nowTime - ChatClient.begintime) > ChatClient.overtime_5) {
                showMsg("有相关记录");
                break;
            }
            UiObject mTV_not_order_list = mDevice.findObject(new UiSelector().className("android.widget.TextView").text
                    ("找不到相关记录"));
            if (mTV_not_order_list.exists()) {
                showMsg("账单页面未刷新出来，返回");
                sleep(ChatClient.overtime_5);
                backMainPage();
                return;
            }
        }
        dragFlag = 1;
        itemInfoList.clear();
        sleep(ChatClient.overtime_5);
        request();
        int itemNum = 0;
        date = Util.getStandardDate(".");
        getView(itemNum);
    }

    private void getView(int itemNum) throws UiObjectNotFoundException {
        while (true) {
            UiObject mSV = mDevice.findObject(new UiSelector().className("android.widget.ScrollView").index(4));
            if (mSV.exists()) {
                UiObject mVGChildList1 = mSV.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
                if (mVGChildList1.exists()) {
                    UiObject mVGChildList2;
                    while (true) {
                        if (dragFlag < 2) {
                            mVGChildList2 = mVGChildList1.getChild(new UiSelector().className("android.view.ViewGroup").index(1));
                        } else {
                            mVGChildList2 = mVGChildList1.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
                        }

                        if (mVGChildList2.exists()) {
                            UiObject mVGChildList3 = mVGChildList2.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
                            if (mVGChildList3.exists()) {
                                UiObject mVGChildList4 = mVGChildList3.getChild(new UiSelector().className("android.view.ViewGroup").index(4));
                                if (mVGChildList4.exists()) {
                                    UiObject mVGChildList = mVGChildList4.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
                                    if (mVGChildList.exists()) {

                                        showMsg("查看第" + itemNum + "条");
                                        sleep(ChatClient.overtime_1);
                                        int isStop;
                                        if (itemNum > 50) {
                                            isStop = 0;
                                        } else {
                                            isStop = itemProcess(mVGChildList, itemNum);
                                        }
                                        if (isStop == 0) {
                                            showMsg("结束查找");
                                            if (itemInfoList.size() > 0) {
                                                showMsg("开始上传");
                                                uploadOrderList();
                                            } else {
                                                showMsg("无需上报订单");
                                            }
                                            return;
                                        } else if (isStop == 1) {
                                            showMsg("继续读取下一条");
                                            itemNum += 1;
                                        }

                                    } else {
                                        showMsg("mVGChildList,未找到");
                                        backMainPage();
                                        return;
                                    }
                                } else {
                                    showMsg("mVGChildList4,未找到");
                                    backMainPage();
                                    return;
                                }
                            } else {
                                showMsg("mVGChildList3,未找到");
                                backMainPage();
                                return;
                            }
                        } else {
                            showMsg("mVGChildList2,未找到");
                            backMainPage();
                            return;
                        }
                    }
                } else {
                    showMsg("mVGChildList1,未找到");
                    backMainPage();
                    return;
                }
            } else {
                showMsg("mSV,未找到");
                backMainPage();
                return;
            }
        }
    }

    private boolean timing() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        System.out.println(simpleDateFormat.format(date));
        if (23 < Integer.valueOf(simpleDateFormat.format(date)) && Integer.valueOf(simpleDateFormat.format(date)) < 1) {
            showMsg("凌晨需要查第二天");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 条目匹配流程
     *
     * @param mVGChildList 列表对象
     * @param itemNum      条目index
     * @return 0：不在继续查询  1：继续查询
     * @throws UiObjectNotFoundException 异常捕获
     */
    private int itemProcess(UiObject mVGChildList, int itemNum) throws UiObjectNotFoundException {
        ChatClient.request();
        UiObject mVG_item = mVGChildList.getChild(new UiSelector().index(itemNum));
        if (itemNum == 0) {//0位条目位账单月份
            if (mVG_item.exists()) {//匹配条目0位是否是当月
                UiObject mVG_item1 = mVG_item.getChild(new UiSelector().index(itemNum).className("android.view.ViewGroup"));
                UiObject child = mVG_item1.getChild(new UiSelector().index(0).className("android.widget.TextView"));
                if (child.exists()) {
                    String text = child.getText().trim();
                    if (date.contains(text)) {//判断日期条目
                        showMsg("匹配年月---" + text);
                        return 1;
                    } else {
                        showMsg("账单为过往年月");
                        return 0;
                    }
                }
            }
        } else {//非第一条
            UiObject child = mVG_item.getChild(new UiSelector().className("android.widget.TextView").index(1));
            if (child.exists()) {
                String text = child.getText().trim();
                showMsg("向上滑动，查看更多====" + text);
                if (text.contains("向上滑动，查看更多")) {
                    showMsg("无更多条目");
                    return 0;
                }
            }
            UiObject itemViewGroup = getItemViewGroup(mVG_item);
            if (itemViewGroup != null && itemViewGroup.exists()) {
                while (true) {
                    UiObject mTV_day = itemViewGroup.getChild(new UiSelector().className("android.widget.TextView").index(0));
                    if (mTV_day.exists()) {
                        String day = mTV_day.getText().trim();
                        String[] strings = date.split("\\.");
                        String date_day = strings[2].trim();
                        showMsg("day---" + day + ",date_day---" + date_day);
                        if (!StringUtils.isEmpty(day) && !day.contains("编辑")) {
                            if (day.equals(date_day) || timing()) {
//                                测试使用 查之前数据
                                showMsg("是当天记录");
                                UiObject mTV_status = findItemView(itemViewGroup);
                                if (mTV_status != null && mTV_status.exists()) {
                                    showMsg("存在转账条目");
                                    mTV_status.click();
                                    if (joinOrderPage()) {
                                        showMsg("进入交易详情页");
                                        boolean noRepeat = orderPage(false);
                                        if (noRepeat) {
                                            showMsg("读取下一条");
                                            back();
                                            return 1;
                                        } else {
                                            showMsg("已到缓存条目，结束读取记录");
                                            back();
                                            return 0;
                                        }
                                    }
                                } else {
                                    showMsg("条目非入账条目");
                                    return 1;
                                }

                            } else {
                                // 当日期非本日，判定有无缓存，有缓存就就是本日第一次上报，直接上传
                                showMsg("非当天记录");
                                return 0;
                            }
                        } else {
                            showMsg("无日期条目");
                            if (itemNum > 4 && carrier.contains("Lenovo L78011")) {
                                UiObject text = getItemViewGroup1(mVG_item, itemNum);
                                if (text != null && text.exists()) {
                                    showMsg("text==" + text.getText());
                                    text.click();
                                } else {
                                    return 1;
                                }
                                if (joinOrderPage()) {
                                    showMsg("进入交易详情页");
                                    boolean noRepeat = orderPage(false);
                                    if (noRepeat) {
                                        showMsg("读取下一条");
                                        back();
                                        return 1;
                                    } else {
                                        showMsg("已到缓存条目，结束读取记录");
                                        back();
                                        return 0;
                                    }
                                } else {
                                    showMsg("未进入交易详情页");
                                }
                            } else {
                                return s5(itemViewGroup);
                            }
                        }
                    } else {//未找到日期控件
                        drag(itemViewGroup);
                        return itemProcess(mVGChildList, itemNum);
                    }
                }
            } else {//未找到条目向上滑动
                if (notFoundClauses > 2) {
                    notFoundClauses = 0;
                    return 0;
                } else {
                    drag(itemViewGroup);
                    return itemProcess(mVGChildList, itemNum);
                }

            }
        }
        return -1;
    }

    private int s5(UiObject itemViewGroup) throws UiObjectNotFoundException {
        UiObject mTV_status = findItemView(itemViewGroup);
        if (mTV_status != null && mTV_status.exists()) {
            showMsg("存在转账条目");
            mTV_status.click();
            if (joinOrderPage()) {
                showMsg("进入交易详情页");
                boolean noRepeat = orderPage(false);
                if (noRepeat) {
                    showMsg("读取下一条");
                    back();
                    return 1;
                } else {
                    showMsg("已到缓存条目，结束读取记录");
                    back();
                    return 0;
                }
            } else {
                showMsg("未进入交易详情页");
            }
        } else {
            showMsg("非入账条目");
            return 1;
        }
        return -1;
    }

    /**
     * 交易详情
     *
     * @return 是否是缓存条目
     */
    private boolean orderPage(boolean isUpload) throws UiObjectNotFoundException {
        ChatClient.request();
        int balance = 0;             //卡上余额
        String machineId = "";           //设备号
        String tradingTime = "";         //交易时间
        String money = "";               //存款金额
        String systemDescription = "";   //系统备注
        String payer = "";               //付款人
        String payerBank = "";           //付款人银行
        String payerCard = "";           //付款人卡号
        String mark = "";                //唯一标识，重复性验证使用  不同银行可能传的Mark不一样
        String numbered = "";            //银行流水号
        String description = "";         //
        if (!TextUtils.isEmpty(bankInfo)) {
            String[] infos = bankInfo.split(" ");
            machineId = infos[1];
        }
        while (true) {
            mDevice.drag(100, screenHeight - 200, 100, 750, 20);
            UiObject mTV_refresh = mDevice.findObject(new UiSelector().className("android.widget.TextView").text("点击刷新界面"));
            if (mTV_refresh.exists()) {
                showMsg("页面未刷新出来，点击刷新");
                mTV_refresh.click();
            } else {
                showMsg("orderPage");
                UiObject mSV = mDevice.findObject(new UiSelector().className("android.widget.ScrollView").index(2));
                if (mSV.exists()) {
                    UiObject mVG_order_info = mSV.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
                    if (mVG_order_info.exists()) {
                        UiObject mVG = mVG_order_info.getChild(new UiSelector().className("android.view.ViewGroup").index(1));
                        if (mVG.exists()) {
                            if (mVG.getChildCount() < 1) {
                                showMsg("无信息页面");
                                return false;
                            }
                            UiObject merchantNameView = mVG.getChild(new UiSelector().className("android.widget.TextView").index(2));
                            if (merchantNameView.exists()) {
                                String merchantName = merchantNameView.getText().trim();
                                if (merchantName.contains("银联扫码转账")) {
                                    showMsg("银联扫码转账");
                                } else {
                                    return true;
                                }
                            }
                            UiObject mTV_time = mVG.getChild(new UiSelector().className("android.widget.TextView").index(6));
                            UiObject mTV_description = mVG.getChild(new UiSelector().className("android.widget.TextView").index(8));
                            UiObject mTV_money = mVG.getChild(new UiSelector().className("android.widget.TextView").index(10));
                            UiObject mTV_payer = mVG.getChild(new UiSelector().className("android.widget.TextView").index(12));
                            UiObject mTV_payerBank = mVG.getChild(new UiSelector().className("android.widget.TextView").index(14));
                            UiObject mTV_payerBankNo = mVG.getChild(new UiSelector().className("android.widget.TextView").index(15));
                            UiObject mTV_card_title = mVG_order_info.getChild(new UiSelector().className("android.widget.TextView")
                                    .text("收单机构"));
                            UiObject mTV_mark;
                            UiObject mTV_refer_num;
                            if (mTV_card_title.exists()) {
                                mTV_mark = mVG_order_info.getChild(new UiSelector().className("android.widget.TextView")
                                        .instance(24));
                                mTV_refer_num = mVG_order_info.getChild(new UiSelector().className("android.widget.TextView")
                                        .index(18));
                            } else {
                                mTV_mark = mVG_order_info.getChild(new UiSelector().className("android.widget.TextView")
                                        .instance(25));
                                mTV_refer_num = mVG_order_info.getChild(new UiSelector().className("android.widget.TextView")
                                        .index(16));
                            }
                            if (mTV_time.exists()) {
                                tradingTime = mTV_time.getText().trim();
                                tradingTime += ":00";
                            }
                            if (mTV_description.exists()) {
                                systemDescription = mTV_description.getText().trim();
                            }
                            if (mTV_money.exists()) {
                                money = mTV_money.getText().trim();
                            }
                            if (mTV_payer.exists()) {
                                payer = mTV_payer.getText().trim();
                            }
                            if (mTV_payerBank.exists()) {
                                payerBank = mTV_payerBank.getText().trim();
                            }
                            if (mTV_payerBankNo.exists()) {
                                payerCard = mTV_payerBankNo.getText().trim();
                                if (!StringUtils.isEmpty(payerCard)) {
                                    payerCard = payerCard.substring(payerCard.length() - 4);
                                }
                            }

                            if (mTV_mark != null && mTV_mark.exists()) {
                                mark = mTV_mark.getText().trim();
                            }
                            if (mTV_refer_num != null && mTV_refer_num.exists()) {
                                numbered = mTV_refer_num.getText().trim();
                            }
                            if (!StringUtils.isEmpty(tradingTime) && !StringUtils.isEmpty(systemDescription) && !StringUtils.isEmpty
                                    (money) && !StringUtils.isEmpty(payer) && !StringUtils.isEmpty(payerBank) &&
                                    !StringUtils.isEmpty(payerCard) && !StringUtils.isEmpty(mark) && !StringUtils.isEmpty(numbered)) {
                                money = money.replaceAll("元", "").replaceAll(",", "");
                                String json = "'machineId':'" + machineId + "','money':'" + money +
                                        "','tradingTime':'" + tradingTime + "','payer':'" + payer + "','payerCard':'" + payerCard +
                                        "', 'payerBank':'" + payerBank + "','mark':'" + mark + "','description':'" + description +
                                        "','systemDescription':'" + systemDescription + "','numbered':'" + numbered + "'" + "," +
                                        "'balance':'" + balance + "'";
                                showMsg("银行账单信息打印完成");
                                //                            showLog("缓存账单信息=======" + Constants.SendResultCacheInfo);
                                if (isUpload) {
                                    return uploadOrder(tradingTime, json);
                                } else {
                                    return addJsonOrList(tradingTime, json);
                                }
                            } else {
                                showMsg("打印收款姓名对比===" + payer);
                                return true;
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 判定是否为缓存记录条目
     *
     * @param json 封装的数据
     * @return 是否有缓存
     */
    private boolean addJsonOrList(String tradingTime, String json) {
        String date = tradingTime.split(" ")[0];
        if (!StringUtils.isEmpty(date)) {
            date = date.replaceAll("-", ".");
            if (timing()) {
                if (!Util.isInquireDate("2", date)) {
                    return false;
                }
            } else {
                if (!Util.isInquireDate("1", date)) {
                    return false;
                }
            }

        }
        // 无账单缓存
        if (itemResultCacheInfoList.isEmpty()) {
            // 添加到上传列表
            showMsg("无缓存Json");
            itemInfoList.add(json);
            return true;
        } else {
            // 有账单缓存
            if (itemResultCacheInfoList.contains(json)) {
                showMsg("以查询到跟之前缓存信息一样，返回上报");
                return false;
            } else {
                showMsg("查询到新的订单信息");
                itemInfoList.add(json);
                //继续读取下一条
                return true;
            }
        }
    }

    /**
     * 上传订单列表逻辑
     */
    private void uploadOrderList() {
        // 上传新的付款订单信息
        Collections.reverse(itemInfoList);
        for (int i = 0; i < itemInfoList.size(); i++) {
            String json = itemInfoList.get(i);
            ChatClient.M_sendTradeInfo_P(json);
            request();
            int flag = 1;
            while (true) {
                if (ChatClient.tradeInfo != null) {
                    if (json.contains(ChatClient.tradeInfo.getMark())) {
                        if (ChatClient.tradeInfo.getCode().equals("100000")) {
                            showMsg("上报成功，储存---" + json);
                            String resultCacheOrderItem = json;
                            itemResultCacheInfoList.add(resultCacheOrderItem);
                            resultCacheOrderItem += "\n";
                            FileHelper.addWriteSDFile(true, resultCacheOrderItem, userOrderListResultCacheFile);
                            break;
                        } else if (ChatClient.tradeInfo.getCode().equals("201030")) {
                            showMsg("上报重复订单---" + json);
                            if (!itemResultCacheInfoList.contains(json)) {
                                showMsg("CacheInfo");
                                String resultCacheOrderItem = json;
                                itemResultCacheInfoList.add(resultCacheOrderItem);
                                resultCacheOrderItem += "\n";
                                FileHelper.addWriteSDFile(true, resultCacheOrderItem, userOrderListResultCacheFile);
                            }
                            break;
                        } else if (ChatClient.tradeInfo.getCode().equals("200000")) {
                            showMsg("上传返回错误第：" + flag + "次，" + ChatClient.tradeInfo.toString());
                            if (flag == 3) {//上报返回错误循环上报3回退出页面继续下一条
                                break;
                            }
                            ChatClient.tradeInfo = null;
                            flag += 1;
                            ChatClient.M_sendTradeInfo_P(json);
                            sleep(ChatClient.overtime_5);
                        }
                    }
                }
            }
        }
        itemInfoList.clear();
        sleep(ChatClient.overtime_3);
        back();
    }

    /**
     * 返回需要查询的条目
     *
     * @param itemViewGroup 父View
     * @return 子view
     * @throws UiObjectNotFoundException 异常捕获
     */
    private UiObject findItemView(UiObject itemViewGroup) throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        long overtime = 3000;
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > overtime) {
                showMsg("未找到条目");
                return null;
            }
            UiObject mTV_order_status = itemViewGroup.getChild(new UiSelector().className("android.widget.TextView").index(4));
            UiObject mTV_order_type = itemViewGroup.getChild(new UiSelector().className("android.widget.TextView").index(6));
            if (mTV_order_status.exists() && mTV_order_type.exists()) {
                String status = mTV_order_status.getText().trim();
                String type = mTV_order_type.getText().trim();
                if (status.contains("其他") && type.contains("银联扫码转账")) {
                    showMsg("银联扫码转账");
                    return mTV_order_status;
                } else {
                    showMsg("找到<" + status + ":" + type + ">非上传条目");
                    return mDevice.findObject(new UiSelector().text("创建一个Null UiObject"));
                }
            } else if (!mTV_order_type.exists() || !mTV_order_status.exists()) {
                showMsg("条目显示不完全,上划");
                drag(itemViewGroup);
                overtime += ChatClient.overtime_3;
            }
        }
    }


    /**
     * 滑动列表，一次只划出一行，然后从新读取
     */
    private void drag(UiObject itemViewGroup) throws UiObjectNotFoundException {
        if (itemViewGroup != null && itemViewGroup.exists()) {
            Rect bounds = itemViewGroup.getBounds();
            //            if (dragFlag == 1) {
            mDevice.drag(30, screenHeight - 150, 30, screenHeight - 150 - (200 * 5) + bounds.height(), 30);
            sleep(ChatClient.overtime_1);
            //            }
        } else {
            mDevice.drag(30, screenHeight - 150, 30, screenHeight - (150 + 500), 30);
            sleep(ChatClient.overtime_1);
        }

        ChatClient.request();
        showMsg("第" + dragFlag + "次滑动列表");
        dragFlag += 1;
    }

    private int notFoundClauses = 0;

    private UiObject getItemViewGroup(UiObject mVG) throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_3) {
                notFoundClauses++;
                showMsg("未找到条目ViewGroup");
                break;
            }
            UiObject child1 = mVG.getChild(new UiSelector().className("android.view.ViewGroup").index
                    (0));
            if (child1.exists()) {
                UiObject child2;
                if (dragFlag > 4 && carrier.contains("Lenovo L38041")) {
                    child2 = child1.getChild(new UiSelector().className("android.view.ViewGroup")
                            .index(1));
                } else {
                    child2 = child1.getChild(new UiSelector().className("android.view.ViewGroup")
                            .index(0));
                }
                if (child2.exists()) {
                    UiObject child3 = child2.getChild(new UiSelector().className("android.view.ViewGroup")
                            .index(0));
                    if (child3.exists()) {
                        UiObject child4 = child3.getChild(new UiSelector().className("android.view.ViewGroup")
                                .index(0));
                        if (child4.exists()) {
                            notFoundClauses = 0;
                            return child4;
                        }
                    }
                }
            }
        }
        return null;
    }

    private UiObject getItemViewGroup1(UiObject mVG, int itemNum) throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_10) {
                showMsg("未找到条目ViewGroup");
                break;
            }
            UiObject child1 = mVG.getChild(new UiSelector().className("android.view.ViewGroup").index
                    (0));
            if (child1.exists()) {
                showMsg("child1");
                UiObject child2 = child1.getChild(new UiSelector().className("android.view.ViewGroup")
                        .index(0));
                if (child2.exists()) {
                    showMsg("child2");
                    return child2.getChild(new UiSelector().className("android.widget.TextView").text("其他"));
                }
            }
        }
        return null;
    }


    private boolean newLogin = true;//重新登录
    private int uploadNum = 0;//上传次数
    private String screenshot = "";//二维码截图地址

    /**
     * 截取收款二维码并上传
     */
    private void handleQRCodeBase64() throws UiObjectNotFoundException {
        if (StringUtils.isEmpty(Constants.QRCodeUpdateTime)) {
            try {
                QRCodeUpdateTimeFile = user.getUserName() + bank_name + "QRCodeTime" + ".txt";
                FileHelper.createSDFile(QRCodeUpdateTimeFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Constants.QRCodeUpdateTime = FileHelper.readSDFile(QRCodeUpdateTimeFile);
        }

        showMsg("Constants.QRCodeUpdateTime===" + Constants.QRCodeUpdateTime);
        addWorkTime(ChatClient.overtime_30);
        if (uploadNum < 1) {
            joinQRCodePage();
        }
        showMsg("需要上传二维码");
        /*
         * 需要截取二维码并上传
         */
        if (StringUtils.isEmpty(screenshot)) {
            screenshot = screenshot();
        }
        if (!StringUtils.isEmpty(screenshot) && new File(screenshot).exists()) {
            /*
             * 二维码字符串上传
             */
            if (uploadNum < 3) {
                showMsg("第" + (uploadNum + 1) + "次截图上传");
                ChatClient.uploadQRCodeBase64(screenshot);
                sleep(ChatClient.overtime_10);
                if (uploadFail()) {
                    showMsg("保存上传二维码时间");
                    FileHelper.writeSDFile(ChatClient.qRCodeUpLoadBean.getSaveTime(), QRCodeUpdateTimeFile);
                    Constants.QRCodeUpdateTime = ChatClient.qRCodeUpLoadBean.getSaveTime();
                    newLogin = false;
                    uploadNum = 0;
                    screenshot = "";
                } else {
                    uploadNum += 1;
                    showMsg("重新进行上传操作");
                    handleQRCodeBase64();
                }
            } else {
                uploadNum = 0;
                screenshot = "";
            }
        } else {
            if (uploadNum < 3) {
                showMsg("二维码截图失败，重新截图");
                screenshot = "";
                handleQRCodeBase64();
            } else {
                showMsg("多次上传失败，过后再来");
            }
        }
    }

    /**
     * 上传返回处理
     *
     * @return true为上传成功，false反之
     */
    private boolean uploadFail() {
        if (ChatClient.qRCodeUpLoadBean != null) {
            String machineId = "";
            if (!TextUtils.isEmpty(bankInfo)) {
                String[] infos = bankInfo.split(" ");
                machineId = infos[1];
            }
            if (!ChatClient.qRCodeUpLoadBean.getMachineId().equals(machineId)) {
                showMsg("machineId不匹配");
                return false;
            }
            if (ChatClient.qRCodeUpLoadBean.getState().equals("0")) {
                showMsg("二维码上传成功");
                return true;
            } else {
                showMsg("State不匹配");
                return false;
            }
        } else {
            showMsg("未收到返回状态");
            return false;
        }
    }

    /**
     * 是否获取二维码
     *
     * @return true为要获取，false为不用获取
     */
    private boolean UpdateQRCode() {
        boolean isUpdate = false;
        if (Util.isTimeOut(Constants.QRCodeUpdateTime)) {
            showMsg("超时截取二维码");
            isUpdate = true;
        } else if (Util.outpaceZero(Constants.QRCodeUpdateTime)) {
            showMsg("不是同天截取二维码");
            isUpdate = true;
        }
        return isUpdate;
    }

    /**
     * 截取二维码
     */
    private String screenshot() {
        Bitmap bitmap = null;
        String imageName = null;
        try {
            LogToFile.d("====输入密码=====", "截图2016");
//            bitmap = ImageView.getImage1(270, 556, 810, 1096, 540, 540);
//             云闪付8.0.5二维码图图片变化
            bitmap = ImageView.getImage1(270, 662, 810, 1202, 540, 540);
            if (bitmap != null) {
                imageName = ImageView.saveImg44(bitmap);
            }
            sleep(2000);
        } catch (Exception e) {
            showMsg("二维码截取失败:" + e.getMessage());
        }
        return imageName;
    }

    /**
     * 点击返回返回上页
     */
    private void back() {
        mDevice.pressBack();
    }

    /**
     * 返回主页
     */
    private void backMainPage() {
        while (true) {
            UiObject mTV_card_manage = mDevice.findObject(new UiSelector().resourceId("com.unionpay:id/tv_tab_name").text("财 富"));
            if (mTV_card_manage.exists()) {
                showMsg("以返回财 富主页");
                String orderListResultCacheFile = user.getUserName() + bank_name + Util.getStandardDate("") + ".txt";
                if (!orderListResultCacheFile.equals(userOrderListResultCacheFile)) {
                    showMsg("DateUpdate");
                    readOrderListFile();
                }
                break;
            } else {
                showMsg("调返回");
                back();
                sleep(ChatClient.overtime_3);
            }
        }
    }

    /**
     * 进入二维码页面
     *
     * @throws UiObjectNotFoundException 异常捕获
     */
    private void joinQRCodePage() throws UiObjectNotFoundException {
        while (true) {
            UiObject mBT_bottom = mDevice.findObject(new UiSelector().resourceId("com.unionpay:id/text").text("收款码"));
            if (mBT_bottom.exists()) {
                showMsg("点击收款码");
                mBT_bottom.click();
                break;
            }
        }
        while (true) {
            UiObject mBT_bottom = mDevice.findObject(new UiSelector().resourceId("com.unionpay:id/layout_p2ptransfer_mcc"));
            if (mBT_bottom.exists()) {
                showMsg("点击商户收款");
                mBT_bottom.click();
                sleep(ChatClient.overtime_2);
                break;
            }
        }
        while (true) {
            UiObject mBT_bottom = mDevice.findObject(new UiSelector().className("android.view.View").text("查看收款码"));
            if (mBT_bottom.exists()) {
                showMsg("点击查看收款码");
                mBT_bottom.click();
                break;
            }
        }
        sleep(ChatClient.overtime_5);
    }

    /**
     * 切换卡管理页面
     *
     * @throws UiObjectNotFoundException 异常捕获
     */
    private void joinOrderListPage() throws UiObjectNotFoundException {
        while (true) {
            UiObject mTV_keyList = mDevice.findObject(new UiSelector().resourceId("com.unionpay:id/tv_tab_name").text("财 富"));
            if (mTV_keyList.exists()) {
                showMsg("切换财 富页");
                mTV_keyList.click();
                sleep(ChatClient.overtime_3);
                break;
            }
        }

        showMsg("准备点击卡片");
        while (true) {
            UiObject textBankOn = mDevice.findObject(new UiSelector().resourceId("com.unionpay:id/fortune_cardbag_number"));
            if (textBankOn.exists()) {
                showMsg("点击卡片");
                textBankOn.click();
                break;
            } else {
                showMsg("找不到卡片>滑动");
                mDevice.drag(700, 1700, 700, 1300, 30);
            }
        }
// 有多张卡是切换卡使用  目前直接上报第一张卡的交易记录 缺少卡号信息 注释掉 2020年5月15日10:11:05
        int count = 1;
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_3) {
                showMsg("bankOn获取失败不影响任何业务");
                break;
            }
            UiObject recyclerView = mDevice.findObject(new UiSelector().className("android.widget.HorizontalScrollView"));
            UiObject relativeLayout = recyclerView.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
            UiObject viewGroup = relativeLayout.getChild(new UiSelector().className("android.view.ViewGroup").index(count));
            UiObject viewGroup1 = viewGroup.getChild(new UiSelector().className("android.view.ViewGroup").index(0));
            UiObject viewGroup2 = viewGroup1.getChild(new UiSelector().className("android.view.ViewGroup").index(2));
            UiObject textBankOn = viewGroup2.getChild(new UiSelector().className("android.widget.TextView").index(1));
            if (textBankOn.exists()) {
                String bankOn = textBankOn.getText().substring(textBankOn.getText().length() - 4);
                showMsg("bankOn=" + bankOn);
                break;
            }
        }
        while (true) {
            UiObject mTV_keyList = mDevice.findObject(new UiSelector().className("android.widget.TextView").text("交易记录"));
            if (mTV_keyList.exists()) {
                showMsg("交易记录");
                mTV_keyList.click();
                sleep(ChatClient.overtime_3);
                break;
            }
        }
    }

    /**
     * 判定进入交易详情页
     *
     * @return true为进入交易详情页，false反之
     */
    private boolean joinOrderPage() {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showMsg("未找到交易页");
                return false;
            }
            UiObject mTV_title = mDevice.findObject(new UiSelector().className("android.widget.TextView").text("交易详情"));
            if (mTV_title.exists()) {
                return true;
            }
        }
    }

    public void showMsg(String msg) {
        LogToFile.showLog(bankName, msg);
    }
}
